import store from '../store/index.js'

// let baseUrl = 'https://www.zhixuanqixing.xyz/applet'
let baseUrl;

if (process.env.NODE_ENV === 'development') {
	console.log('开发环境')
	// baseUrl = 'https://www.zhixuanqixing.xyz/applet'
	baseUrl = 'http://127.0.0.1:5050/applet'
} else {
	console.log('生产环境')
	baseUrl = 'https://www.zhixuanqixing.xyz/applet'
}

// 全局请求封装
export default (path, data = {}, reqType = 'POST', ) => {
	// console.log(path, data, reqType)
	const token = uni.getStorageSync("token");
	const Authorization = token ? `Bearer ${uni.getStorageSync("token")}` : "";

	return new Promise((resolve, reject) => {
		uni.request({
			header: {
				Authorization
			},
			url: baseUrl + path,
			method: reqType,
			data,
			// timeout: 3000,
			success(response) {
				console.log(response)
				// #ifdef MP-WEIXIN
				if (response.statusCode !== 200) {
					let title = ''
					//http状态码
					const status = response.statusCode
					console.log(status)
					switch (status) {
						case 401:
							title = '无权访问'
							break
						case 403:
							title = '无权访问'
							break
						case 404:
							title = '请求地址错误'
							break
						case 500:
							title = '服务器出现问题'
							break
						default:
							title = '网络出现问题'
							break
					}
					uni.showToast({
						icon: "fail",
						title,
						duration: 2000
					});
					if (status === 401 || status === 403) {
						store.commit('clearUserInfo')
						uni.redirectTo({
							url: '/pages/login/login'
						})
					}
					return
				} else if (response.data.status === 1) {
					uni.showToast({
						icon: "fail",
						title: response.data.msg,
						duration: 2000
					});
					return
				}
				// #endif
				resolve(response.data);
			},
			fail(err) {
				console.log(err)
				//失败回调:处理http网络错误的
				//定义一个变量:存储网络错误信息
				let title = ''
				//http状态码
				const status = err.statusCode
				console.log(status)
				switch (status) {
					case 401:
						title = '无权访问'
						break
					case 403:
						title = '无权访问'
						break
					case 404:
						title = '请求地址错误'
						break
					case 500:
						title = '服务器出现问题'
						break
					default:
						title = '网络出现问题'
						break
				}
				uni.showToast({
					icon: "fail",
					title,
					duration: 2000
				});
				if (status === 401 || status === 403) {
					store.commit('clearUserInfo')
					uni.redirectTo({
						url: '/pages/login/login'
					})
				}
				return
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
};
